<?php

// phpMyRealty 3
//
// File Name: submit.php
// File Location : ./
//
// Copyright (c)2009 phpMyRealty.com
//
// e-mail: support@phpMyRealty.com

// Include configuration file and general functions
define('PMR', 'true');

$page = 'register';

include ( './config.php' );
include ( PATH . '/defaults.php' );

generateCaptcha();

$rand = mt_rand(1, 999);

// ----------------------------------------------------------------------
// SUBMIT USER SECTION

// Title tag content
$title = $conf['website_name_short'] . ' - ' . $lang['Menu_Submit_Listing'];

// Template header
include ( PATH . '/templates/' . $cookie_template . '/header.php' );

// Submit Realtor

// If the Submit button was pressed we start this routine
if (isset($_POST['submit_realtor'])
&& $_POST['submit_realtor'] == $lang['Realtor_Submit'])
 {

  $form = array();

  // safehtml() all the POST variables
  // to insert into the database or
  // print the form again if errors
  // found
  $form = array_map('safehtml', $_POST);

  // Make login and password lower case
  $login = strtolower ($_POST['realtor_login']);
  $password = $_POST['realtor_password'];

  // Cut the description size to the allowed minimum set in config
  $form['Realtor_Description'] = substr ($form['realtor_description'], 0, $conf['realtor_description_size']);

  echo table_header ( $lang['Information'] );

  // Initially we think that no errors were found
  $count_error = 0;

  if ( strtoupper($_POST['security']) != $_SESSION['random'] )
   { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Security_Code'] . ' </span><br />'; $count_error++;}

  // Check for the empty or incorrect required fields
  if (empty($form['realtor_first_name']) || strlen($form['realtor_first_name']) < 2 )
   { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Realtor_First_Name'] . '</span><br />'; $count_error++;}

  if (empty($form['realtor_last_name']) || strlen($form['realtor_last_name']) < 2 )
   { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Realtor_Last_Name'] . '</span><br />'; $count_error++;}

  if (empty($form['realtor_city']) || strlen($form['realtor_city']) < 2 )
   { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['City'] . '</span><br />'; $count_error++;}

  if (empty($form['realtor_address']) || strlen($form['realtor_address']) < 4 )
   { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Realtor_Address'] . '</span><br />'; $count_error++;}

  if (empty($form['realtor_zip_code']) || strlen($form['realtor_zip_code']) < 4 )
   { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Zip_Code'] . '</span><br />'; $count_error++;}

  if (empty($form['realtor_phone']) || strlen($form['realtor_phone']) < 4 )
   { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Realtor_Phone'] . '</span><br />'; $count_error++;}

  if (empty($form['realtor_e_mail']) || strlen($form['realtor_e_mail']) < 4  || !valid_email($form['realtor_e_mail']))
   { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Realtor_e_mail'] . '</span><br />'; $count_error++;}

  if (empty($form['realtor_login']) || strlen($form['realtor_login']) < 4 )
   { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Realtor_Login'] . '</span><br />'; $count_error++;}

  if (empty($form['realtor_password']) || strlen($form['realtor_password']) < 4 )
   { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Realtor_Password'] . '</span><br />'; $count_error++;}

  // Check if login is already exist
  $sql = 'SELECT login FROM ' . USERS_TABLE . ' WHERE login = "' . safehtml($login) . '"';
  $r = $db->query($sql) or error ('Critical Error', mysql_error () );

  if ($db->numrows($r) > 0 )
   { echo $lang['Login_Used'] . '<br />'; $count_error++;}

  // Check if email is banned
  $sql = 'SELECT * FROM ' . BANS_TABLE . ' WHERE name = "' . $form['realtor_e_mail'] . '" LIMIT 1';
  $r = $db->query($sql) or error ('Critical Error', mysql_error () );

  if ($db->numrows($r) > 0 )
   { echo $lang['e_mail_Banned'] . '<br />'; $count_error++;}

  // Check if this email is already used
  if (strcasecmp($conf['allow_same_e_mail'], 'ON')) {
     $sql = 'SELECT id FROM ' . USERS_TABLE . ' WHERE email = "' . $form['realtor_e_mail'] . '"';
     $r = $db->query($sql) or error ('Critical Error', mysql_error () );

     if ($db->fetcharray($r) > 0 )
      { echo $lang['Email_Used'] . '<br />'; $count_error++;}
  }

  if (!eregi('^[a-z0-9]+$', $login))
   { echo $lang['Login_Incorrect'] . '<br />'; $count_error++;}

  if (!eregi('^[a-z0-9]+$', $password))
   { echo $lang['Password_Incorrect'] . '<br />'; $count_error++;}

  // Check if both passwords are equal
  if ($form['realtor_password'] != $form['realtor_password_2'])
   { echo $lang['Passwords_Missmatch'] . '<br />'; $count_error++;}

  if ($count_error > '0')
   echo '<br /><span class="warning">' . $lang['Errors_Found'] . ': ' . $count_error . '</span><br />';

  // If no errors were found during the above checks we continue
  if ($count_error == '0')
   {

    // Add realtor listing into the database

    if ($conf['approve_realtors'] == 'ON')
     $approved = 0;
    else
     // if you want all the new accounts to be approved without admin or email
     // validation, please, set the following variable $approved to 1
     $approved = 0;

    // Get the user IP address
    $user_ip = $_SERVER['REMOTE_ADDR'];
    // If there is more than one IP
    // get the first one from the
    // comma separated list
    if ( strstr($user_ip, ', ') )
     {
      $ips = explode(', ', $user_ip);
      $user_ip = $ips[0];
     }

    // Generate random number for the email validation link
    $number = rand (1000000, 9999999);

    // Create a mysql query
    $sql = 'INSERT INTO '. USERS_TABLE .
      ' (approved, first_name, last_name, company_name,
    description, location, city, zip, address,
    phone, fax, mobile, email, website, rating,
    votes, date_added, ip_added, login, password, number) VALUES
    (' . $approved . ', "' . $form['realtor_first_name'] . '", "' . $form['realtor_last_name']. '", "' . $form['realtor_company_name'] . '", "'
    . $form['realtor_description'] . '", ' . $form['realtor_location'] . ', "' . $form['realtor_city'] . '", "' . $form['realtor_zip_code'] . '", "' . $form['realtor_address'] . '", "'
    . $form['realtor_phone'] . '", "' . $form['realtor_fax'] . '", "' . $form['realtor_mobile'] . '", "' . $form['realtor_e_mail'] . '", "' . $form['realtor_website'] . '", 0,
     0, "' . date ('Y-m-d') . '", "' . $user_ip . '", "' . $login . '", "' . md5($password) . '", "' . $number . '")';

    $db->query($sql) or error ('Critical Error', mysql_error ());

    // Fetch the last auto incremented listing id
    $id = mysql_insert_id();

    if ( strtoupper($_POST['security']) == $_SESSION['random'] ) $session->varunset('random');

    // Output the 'Thank you' message
    // depending on the 'approve_realtors'
    // configuration setting
    if ($conf['approve_realtors'] == 'ON')
     {
      echo $lang['Realtor_Listing_Submitted_Approve'];

//

      $mail = new PHPMailer();

      if(PHPMAILER == '3') {
       $mail->IsSMTP(); // set mailer to use SMTP
       $mail->Host = $smtp['host'];  // specify main and backup server
       $mail->SMTPAuth = true;     // turn on SMTP authentication
       $mail->Username = $smtp['login'];  // SMTP username
       $mail->Password = $smtp['password']; // SMTP password
      }
      elseif(PHPMAILER == '2') {
       $mail->IsSendmail(); // set mailer to use SMTP
      }
      else {
      }

      $mail->From = $conf['general_e_mail'];
      $mail->FromName = $conf['general_e_mail_name'];
      $mail->AddAddress($conf['general_e_mail']);

      $mail->Subject = $lang['Admin_Realtor_Notification_Subject'];

      // Replacing the variable names
      $lang['Admin_Realtor_Notification_Mail'] = str_replace('{first_name}', $form['realtor_first_name'], $lang['Admin_Realtor_Notification_Mail']);
      $lang['Admin_Realtor_Notification_Mail'] = str_replace('{last_name}', $form['realtor_last_name'], $lang['Admin_Realtor_Notification_Mail']);
      $lang['Admin_Realtor_Notification_Mail'] = str_replace('{company}', $form['realtor_company_name'], $lang['Admin_Realtor_Notification_Mail']);
      $lang['Admin_Realtor_Notification_Mail'] = str_replace('{address}', $form['realtor_address'] . ' ' . $form['realtor_city'] . ' ' . $form['realtor_zip_code'] . ' ' . getnamebyid(LOCATIONS_TABLE, $form['realtor_location']), $lang['Admin_Realtor_Notification_Mail']);

      $mail->MsgHTML = $lang['Admin_Realtor_Notification_Mail'];
      $mail->AltBody = removehtml($lang['Admin_Realtor_Notification_Mail']);

      $mail->Send();

     }
    else
     echo $lang['Realtor_Listing_Submitted'];

//

    $mail = new PHPMailer();

    if(PHPMAILER == '3') {
     $mail->IsSMTP(); // set mailer to use SMTP
     $mail->Host = $smtp['host'];  // specify main and backup server
     $mail->SMTPAuth = true;     // turn on SMTP authentication
     $mail->Username = $smtp['login'];  // SMTP username
     $mail->Password = $smtp['password']; // SMTP password
    }
    elseif(PHPMAILER == '2') {
     $mail->IsSendmail(); // set mailer to use SMTP
    }
    else {
    }

    $mail->From = $conf['general_e_mail'];
    $mail->FromName = $conf['general_e_mail_name'];
    $mail->AddAddress($form['realtor_e_mail']);

    $lang['Realtor_Notification_Subject'] = str_replace('{website_name}', $conf['website_name'], $lang['Realtor_Notification_Subject']);
    $mail->Subject = $lang['Realtor_Notification_Subject'];

    $body = $lang['Realtor_Notification_Mail'];
    if (stripos('<br', $body) === false) {
        $body = nl2br($body);
    }

    // Replacing the variable names
    $body = str_replace('{website_name}', $conf['website_name'], $body);
    $body = str_replace('{first_name}', $form['realtor_first_name'], $body);
    $body = str_replace('{last_name}', $form['realtor_last_name'], $body);
    $body = str_replace('{company}', $form['realtor_company_name'], $body);
    $body = str_replace('{address}', $form['realtor_address'] . ' ' . $form['realtor_city'] . ' ' . $form['realtor_zip_code'] . ' ' . getnamebyid(LOCATIONS_TABLE, $form['realtor_location']), $body);
    $body = str_replace('{login}', $login, $body);
    $body = str_replace('{password}', $password, $body);

    if ($conf['approve_realtors'] == 'ON')
     {
      $body = str_replace('{verify}', '', $body);
      $mail->MsgHTML = $body;
      $mail->AltBody = removehtml($body);
     }
    else
     {

      // Send a validation link if approval by admin is disabled
      $validateLink = '<a href="'.URL.'/validate.php?id='.$number.'">'
                      .URL.'/validate.php?id='.$number.'</a>';
      if (strpos($body, '{verify}') === false) {
          $body .= $lang['verify']."<br />\r\n".$validateLink;

      } else {
          $body = str_replace('{verify}', $lang['verify']."<br />\r\n".$validateLink, $body);
      }

      $mail->MsgHTML = $body;
      $mail->AltBody = removehtml($body);
     }

    $mail->Send();

   }

  echo table_footer ( );


  if ($count_error == '0')
   {

    // Fetch all packages to show the paypal forms
    $sql = 'SELECT * FROM ' . PACKAGES_AGENT_TABLE;
    $r_packages = $db->query($sql) or error ('Critical Error', mysql_error () );

    if ($db->numrows($r_packages) > 0) {
        echo table_header ( $lang['Upgrade_Listing'] );
    }

    switch ($conf['paypal_mode']) {
    case 'TEST':
        $paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
        break;
    case 'LIVE':
        $paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
        break;
    default:
        error('Configuration Error', 'paypal_mode can only be either LIVE or TEST. Check configuration screen.');
    }

    while ($f_packages = $db->fetcharray($r_packages))
     {

     // Do not show package we already have
     // if ($f_featured['package'] != $f_packages['id'])

      if ($conf['gateway'] == '2')
       echo '

       <form method="post" action="' . $conf['2co_gateway'] . '">
       <input type="submit" class="submit" value="' . $f_packages['name'] . ' (' . $f_packages['price'] . ')">
       <input type="hidden" name="sid" value="' . $conf['2co_user_id'] . '">
       <input type="hidden" name="product_id" value="' . $f_packages['position'] . '">
       <input type="hidden" name="quantity" value="1">
       <input type="hidden" name="merchant_order_id" value="USER-' . $session->fetch('login') . '-' . $id . '-' . $f_packages['id'] . '">
       </form>&nbsp;&nbsp;';

      if ($conf['gateway'] == '1')
       echo '

       <form action="'.$paypal_url.'" method="post">
       <input type="hidden" name="cmd" value="_xclick">
       <input type="hidden" name="business" value="' . $conf['paypal_email'] . '">
       <input type="hidden" name="return" value="' . URL . '/paypal-agents.php">
       <input type="hidden" name="notify_url" value="' . URL . '/paypal-agents.php">
       <input type="hidden" name="cancel_return" value="' . URL . '"> 
       <input type="hidden" name="invoice" value="' . date ( "YmdHis" ) . '">
       <input type="hidden" name="custom" value="' . $id . ':' . $f_packages['id'] . '">
       <input type="hidden" name="currency_code" value="' . $conf['paypal_currency'] . '">
       <input type="hidden" name="item_name" value="' . $f_packages['name'] . ' (' . $login . ')">
       <input type="hidden" name="quantity" value="1">
       <input type="hidden" name="amount" value="' . $f_packages['price'] . '">
       <input type="hidden" name="no_shipping" value="1">
       <input type="hidden" name="rm" value="2">
       <input type="submit" class="submit" value="' . $f_packages['name'] . '">
       </form>&nbsp;&nbsp;';

     }
     if ($db->numrows($r_packages) > 0) {
        echo '<br />';
        echo table_footer ();
     }
     $db->freeresult($r_packages);
   }

 }

// If we open submit.php for the first time
// or there were errors found in the form fields
// we output the form again with the old variables
// included
if (!isset($count_error) || $count_error > '0')

 {

  echo table_header ( $lang['Menu_Submit_Listing'] );

  // Define the form variables if the form is loaded for the first time
  if (!isset($form))
   {
    $form = array();
    $form['realtor_first_name'] = '';
    $form['realtor_last_name'] = '';
    $form['realtor_company_name'] = '';
    $form['realtor_description'] = '';
    $form['realtor_location'] = '';
    $form['realtor_city'] = '';
    $form['realtor_address'] = '';
    $form['realtor_zip_code'] = '';
    $form['realtor_phone'] = '';
    $form['realtor_fax'] = '';
    $form['realtor_mobile'] = '';
    $form['realtor_e_mail'] = '';
    $form['realtor_website'] = '';
    $form['realtor_login'] = '';
    $form['realtor_password'] = '';
   }

  // Output the form
  echo '
   <form action="' . URL . '/submit.php" method="POST">
    <table width="100%" cellpadding="5" cellspacing="0" border="0">
       ';

  echo userform ($lang['Realtor_First_Name'], '<input type="text" size="45" name="realtor_first_name" value="' . $form['realtor_first_name'] . '" maxlength="255">', '1');
  echo userform ($lang['Realtor_Last_Name'], '<input type="text" size="45" name="realtor_last_name" value="' . $form['realtor_last_name'] . '" maxlength="255">', '1');
  echo userform ($lang['Realtor_Company_Name'], '<input type="text" size="45" name="realtor_company_name" value="' . $form['realtor_company_name'] . '" maxlength="255">');
  echo userform ($lang['Realtor_Description'], '<textarea wrap="soft" cols="45" rows="10"  name="realtor_description" onKeyDown="textCounter(this.form.realtor_description,this.form.realtor_description_counter, ' . $conf['realtor_description_size'] . ');" onKeyUp="textCounter(this.form.realtor_description,this.form.realtor_description_counter, ' . $conf['realtor_description_size'] . ');">' . unsafehtml($form['realtor_description']) . '</textarea>');
  echo userform ('', '<input readonly type="text" name="realtor_description_counter" size="5" maxlength="5" value="' . $conf['realtor_description_size'] . '"> ' . $lang['Characters_Left']);
  echo userform ($lang['Location'], '<select name="realtor_location">' . generate_options_list(LOCATIONS_TABLE, $form['realtor_location']) . '</select>', '1');
  echo userform ($lang['City'], '<input type="text" size="45" name="realtor_city" value="' . $form['realtor_city'] . '" maxlength="50">', '1');
  echo userform ($lang['Realtor_Address'], '<input type="text" size="45" name="realtor_address" value="' . $form['realtor_address'] . '" maxlength="255">', '1');
  echo userform ($lang['Zip_Code'], '<input type="text" size="45" name="realtor_zip_code" value="' . $form['realtor_zip_code'] . '" maxlength="20">', '1');
  echo userform ($lang['Realtor_Phone'], '<input type="text" size="45" name="realtor_phone" value="' . $form['realtor_phone'] . '" maxlength="50">', '1');
  echo userform ($lang['Realtor_Fax'], '<input type="text" size="45" name="realtor_fax" value="' . $form['realtor_fax'] . '" maxlength="50">');
  echo userform ($lang['Realtor_Mobile'], '<input type="text" size="45" name="realtor_mobile" value="' . $form['realtor_mobile'] . '" maxlength="50">');
  echo userform ($lang['Realtor_e_mail'], '<input type="text" size="45" name="realtor_e_mail" value="' . $form['realtor_e_mail'] . '" maxlength="50">', '1');
  echo userform ($lang['Realtor_Website'], '<input type="text" size="45" name="realtor_website" value="' . $form['realtor_website'] . '" maxlength="255">');

  echo userform ($lang['Security_Code'], '<img src="' . URL . '/security.php?' . $rand . '" border="0" alt=""><input type="text" size="25" name="security" value="" maxlength="255">' , '1');

  echo userform ($lang['Realtor_Login'], '<input type="text" size="45" name="realtor_login" value="' . $form['realtor_login'] . '"maxlength="50">', '1');
  echo userform ($lang['Realtor_Password'], '<input type="password" size="45" name="realtor_password" maxlength="50">', '1');
  echo userform ($lang['Realtor_Password_Repeat'], '<input type="password" size="45" name="realtor_password_2" maxlength="50">', '1');
  // Submit button
  echo userform ('', '<input type="Submit" class="submit" name="submit_realtor" value="' . $lang['Realtor_Submit'] . '">');

  echo '
    </table>
   </form>
       ';

  echo table_footer ();

 }

// Template footer
include ( PATH . '/templates/' . $cookie_template . '/footer.php' );

?>